package com.lagou.server.common.service;


import com.lagou.registry.ZookeeperRegistryClient;
import com.lagou.server.common.Operation;

import java.lang.reflect.Method;
import java.util.Arrays;


public class RpcOperation extends Operation {


    private String host;

    private int port;

    public String getHost() {
        return host;
    }

    public void setHost(String host) {
        this.host = host;
    }

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }

    /**
     * 调用类名
     */
    private  String className;

    /**
     * 调用方法名
     */
    private  String methodName;

    /**
     * 参数类型
     */
    private Class<?>[] parameterTypes;
    /**
     * 入参
     */
    private Object[] parameters;



    @Override
    public RpcOperationResult execute() {
        RpcOperationResult rpcOperationResult = new RpcOperationResult();

        ZookeeperRegistryClient registry = ZookeeperRegistryClient.getInstance();
        registry.setHostByservicePath("/"+className+"/"+host+":"+port);
        try {

            //从注册表中获取服务名称
            Class serviceClass = registry.getServiceByName(className);

            Method method = serviceClass.getMethod(methodName, parameterTypes);
            Object result = method.invoke(serviceClass.newInstance(), parameters);
            rpcOperationResult.setResult(result);
            rpcOperationResult.setSuccess(true);

        } catch (Exception e) {
            e.printStackTrace();
            rpcOperationResult.setErrors(e.getMessage());
            rpcOperationResult.setSuccess(false);
        }


        return rpcOperationResult;
    }

    @Override
    public String toString() {
        return "RpcOperation{" +
                "className='" + className + '\'' +
                ", methodName='" + methodName + '\'' +
                ", parameterTypes=" + Arrays.toString(parameterTypes) +
                ", parameters=" + Arrays.toString(parameters) +
                '}';
    }



    public String getClassName() {
        return className;
    }

    public void setClassName(String className) {
        this.className = className;
    }

    public String getMethodName() {
        return methodName;
    }

    public void setMethodName(String methodName) {
        this.methodName = methodName;
    }

    public Class<?>[] getParameterTypes() {
        return parameterTypes;
    }

    public void setParameterTypes(Class<?>[] parameterTypes) {
        this.parameterTypes = parameterTypes;
    }

    public Object[] getParameters() {
        return parameters;
    }

    public void setParameters(Object[] parameters) {
        this.parameters = parameters;
    }
}
